/**
 * @file   modules/board/js/board.js
 * @author NHN (developers@xpressengine.com)
 * @brief  board 모듈의 javascript
 **/

/* complete tp insert document */
function completeDocumentInserted(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var category_srl = ret_obj['category_srl'];

    //alert(message);

    var url;
    if(!document_srl)
    {
        url = current_url.setQuery('mid',mid).setQuery('act','');
    }
    else
    {
        url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    }
    if(category_srl) url = url.setQuery('category',category_srl);
    location.href = url;
}

/* delete the document */
function completeDeleteDocument(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var page = ret_obj['page'];

    var url = current_url.setQuery('mid',mid).setQuery('act','').setQuery('document_srl','');
    if(page) url = url.setQuery('page',page);

    //alert(message);

    location.href = url;
}

/* document search */
function completeSearch(ret_obj, response_tags, params, fo_obj) {
    fo_obj.submit();
}

function completeVote(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    alert(message);
    location.href = location.href;
}

// current page reload
function completeReload(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];

    location.href = location.href;
}

/* complete to insert comment*/
function completeInsertComment(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var comment_srl = ret_obj['comment_srl'];

    var url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    if(comment_srl) url = url.setQuery('rnd',comment_srl)+"#comment_"+comment_srl;

    //alert(message);

    location.href = url;
}

/* delete the comment */
function completeDeleteComment(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var page = ret_obj['page'];

    var url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    if(page) url = url.setQuery('page',page);

    //alert(message);

    location.href = url;
}

/* delete the trackback */
function completeDeleteTrackback(ret_obj) {
    var error = ret_obj['error'];
    var message = ret_obj['message'];
    var mid = ret_obj['mid'];
    var document_srl = ret_obj['document_srl'];
    var page = ret_obj['page'];

    var url = current_url.setQuery('mid',mid).setQuery('document_srl',document_srl).setQuery('act','');
    if(page) url = url.setQuery('page',page);

    //alert(message);

    location.href = url;
}

/* change category */
function doChangeCategory() {
    var category_srl = jQuery('#board_category option:selected').val();
    location.href = decodeURI(current_url).setQuery('category',category_srl).setQuery('page', '');
}

/* scrap */
function doScrap(document_srl) {
    var params = new Array();
    params["document_srl"] = document_srl;
    exec_xml("member","procMemberScrapDocument", params, null);
}


jQuery(function($){
	$(document.body).click(function(e){
		var t=$(e.target),act,params={};

		if(t.parents('.layer_voted_member').length==0 && !t.is('.layer_voted_member')){
			$('.layer_voted_member').hide().remove();
		}

		if(!t.is('a[class^=voted_member_]')) return;

		var srl = parseInt(t.attr('class').replace(/[^0-9]/g,''));
		if(!srl) return;

		if(t.hasClass('comment')){
			act = 'comment.getCommentVotedMemberList';
			params = {'comment_srl':srl,'point':(t.hasClass('votedup')?1:-1)};
		}else{
			act = 'document.getDocumentVotedMemberList';
			params = {'document_srl':srl,'point':(t.hasClass('votedup')?1:-1)};
		}

		$.exec_json(act, params, function(data){
				var l = data.voted_member_list;
				var ul = [];

				if(!l || l.length==0) return;

				$.each(l,function(){
					ul.push(this.nick_name);
				});

				t.after($('<ul>')
					.addClass('layer_voted_member')
					.css({'position':'absolute','top':e.pageY+5,'left':e.pageX})
					.append('<li>'+ul.join('</li><li>')+'</li>'));
			});
	});


	setAnchorPopup();
});

function showTransList(parent_srl){

	//alert(parent_srl);
	//alert(jQuery('.parent_' + parent_srl));

	//var val = jQuery('.parent_' + parent_srl).css('display');

	jQuery('.parent_' + parent_srl).animate(
		    {height: "toggle", opacity: "toggle"},
		    "slow"
		  );

	/*
	if(val == 'none'){
		jQuery('.parent_' + parent_srl).css('display','block');
		//jQuery('.parent_' + parent_srl).animate({"display": "block"});


	} else {
		jQuery('.parent_' + parent_srl).css('display','none');
		//jQuery('.parent_' + parent_srl).animate({"display": "none"});
	}
*/


}

function setAnchorPopup(){

	//onmouseover="showAnchorPopup(${2},e);"

		jQuery('.anchor_tag').mouseover(function(e){

			//alert(e.pageX);
			//alert(e.pageY);

			var anchorId = jQuery(this).attr("val");

			var contents = jQuery('div#anchor_' + anchorId + " > div");
			var name = jQuery('div#anchor_name_' + anchorId);
			var time = jQuery('div#anchor_time_' + anchorId);


			var html = name.html() + "&nbsp;&nbsp;" + time.html();

			html += "<hr>";
			html += contents.html();


			jQuery('#anchor_popup_div').html(html);
			jQuery('#anchor_popup_div').css({'top':(e.pageY - 130) +'px','left':(e.pageX - 110) +'px','position':'absolute'}).show();

		});

		jQuery('.anchor_tag').mouseout(function(e){


			jQuery('#anchor_popup_div').hide();


		});



}

function showAnchorPopup(anchorId,e){


	alert(e.x);
	alert(e.y);

	var popData = jQuery('#anchor_' + anchorId + " .xe_content").clone();

	var offset = jQuery('#popup_anchor_' + anchorId).offset();

	//alert(offset.top);
	//alert(offset.left);

	jQuery('body').append(popData);

	popData.css({'top':'1000px','left':'200px','position':'absolute'}).show();


//
	//alert(popData);
	//jQuery('#popup_anchor_' + anchorId).append(popData);


}


var transRunFlagArray = new Array();
var transResultArray = new Array();
var transRunFlag = false;


//function autoTrans(comment_srl, mid, document_srl, content){
function autoTrans(comment_srl, country, aObj){

	//'act','dispBoardReplyComment','comment_srl',

	//alert(comment_srl);
	//var form = jQuery("#write_comment");

	//insert_comment(form);
	//event.preventDefault();


	var orgCode = "ja";
	var tarCode = "ja";

	/*
	if(orgCountry == "china"){
		orgCode = "zh-CN";
	} else if(orgCountry == "japan"){
		orgCode = "ja";
	} else if(orgCountry == "korea"){
		orgCode = "ko";
	}
	*/

	if(country == "china"){
		tarCode = "zh-CN";
	} else if(country == "japan"){
		tarCode = "ja";
	} else if(country == "korea"){
		tarCode = "ko";
	}


	var transObj = jQuery("#parent_" + comment_srl + "_" + country);

	if(0 < transObj.size()){

		transRunFlag = false;

		//showTransList(comment_srl);
		jQuery('.parent_' + comment_srl).animate(
			    {height: "show", opacity: "show"},
			    "slow"
			  );

		//aObj.href= "#parent_" + comment_srl + "_" + country;

	} else {

		var transRunKey = comment_srl + "_" + country;
		//var trnasBtnID = comment_srl + "_" + orgCountry + "_" + country;
		var flag = false;

		for(var i = 0; i<transRunFlagArray.length; i++){
			if(transRunKey == transRunFlagArray[i]){
				flag = true;



				break;
			}
		}

		if(flag){

			transPopupShow(transResultArray[transRunKey], transRunKey);

			return;
		} else {
			transRunFlagArray[transRunFlagArray.length] = transRunKey;

			transRunFlag = true;
		}

		var comment = jQuery("#comment_text_" + comment_srl + " div div").html();

		//var sourceText = escape(comment);
		var sourceText = comment;

		 //var source = 'https://www.googleapis.com/language/translate/v2?key=AIzaSyAvDF2SJLjjKQPj0LM7WZOFAA66pYrq1tE&source=' + orgCode + '&target=' + tarCode + '&callback=translateText&q=' + sourceText;
		//var source = 'https://www.googleapis.com/language/translate/v2?key=AIzaSyAvDF2SJLjjKQPj0LM7WZOFAA66pYrq1tE&source=' + orgCode + '&target=' + tarCode + '&q=' + sourceText;

		var trans_result = "";
		var apiKey = "AIzaSyAvDF2SJLjjKQPj0LM7WZOFAA66pYrq1tE";
		var langSource = orgCode;
		var langTarget = tarCode;
	 // The language Google will translate the text in.
		var apiurl = "https://www.googleapis.com/language/translate/v2";
		var text = sourceText;


		new jQuery.ajax({
			async:false,
			url: apiurl,
			dataType: 'jsonp',
			//data: { q: sourceText, source: langSource, target: langTarget, key :  apiKey},   // '|es' for auto-detect
			data: { q: sourceText, target: langTarget, key :  apiKey},   // '|es' for auto-detect
			type: "GET",
			//dataType: "json",
			//json: 'callback',
			success: function(response){

				if(response.error){
					//alert(response.error.message);
					trans_result = "translation error";
				} else {
					//alert("aaa1");
					//document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText
					trans_result = response.data.translations[0].translatedText;
				}

				transResultArray[transRunKey] = trans_result;
				//alert(trans_result);

				transPopupShow(trans_result, transRunKey);

				//alert(jQuery("iframe").attr("id"));

				//jQuery("iframe").contents().find("#comment_content_text").html(trans_result);
				//input_area xpress_xeditor_editing_area_container
				jQuery(".input_area iframe").contents().find("#comment_content_text").html(trans_result);

				jQuery("#userName").val("Google");
				jQuery("#parent_srl").val(comment_srl);
				jQuery("#rad_country_" + country).attr('checked', 'checked');


				var form = document.forms["write_comment"];

				procFilter(form, insert_comment);
			},
			error: function(response){
				//alert("aaa2");
				trans_result = "";

			}
		});



	}




	//insert_comment(form);


	/*
	var country = "japan";

	new $.ajax({
		async:false,
		url: "./",
		cache: false,
		scriptCharset: 'utf-8',
		data:{parent_srl : comment_srl, document_srl : document_srl, act : 'dispBoardReplyComment', mid : mid, content : content, country : country},
		type: "GET",
		dataType: "json",
		json: 'callback',
		success: autoTransSuccess,
		error: handleError
	});
	*/

}

function transPopupShow(text, transRunKey){

	var aBtn = jQuery('#' + transRunKey);

	var html = "<div style='width:100%;text-align:right'><a href='javascript:void(0);' onclick='transPopupHidden();'>X</a></div>";

	html += '<div>';
	html += text;
	html += '</div>';

	jQuery('#anchor_popup_div').html(html);
	jQuery('#anchor_popup_div').css({'top':(aBtn.offset().top - 130) +'px','left':(aBtn.offset().left - 200) +'px','position':'absolute'}).show();


}

function transPopupHidden(){
	jQuery('#anchor_popup_div').hide();
}

function translateText(response) {

	if(response.error){
		alert(response.error.message);
	} else {
		document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
	}
 }

